<?php

namespace app\reward\controllers;

use mini\Session;

class Reward
{
    /**
     * 奖励首页
     */
    public function index()
    {
        login_check();

        $user_id = session('user_id');
        $user    = model('user')->find($user_id);
        $signed  = self::signed();
        $time_diff = self::timeDiff();

        if ($signed) {
            $data['last_sign_time'] = $time_diff;
            if ($time_diff < 24) {
                $data['signed'] = true;
            }
        }

        $data['page_title'] = '奖励';
        $data['user']       = $user;

        // 使用公共模板
        template('public', $data);
    }

    /**
     * 签到，登录奖励
     */
    public function sign()
    {
        login_check();

        $user_id = session('user_id');
        $reward = model('reward');
        $signed  = self::signed();
        $time_diff = self::timeDiff();

        if ($signed && $time_diff <= 24) {  
            return json('今日已经签到');
        }

        $data = [
            'user_id'    => $user_id,
            'updated_at' => time(),
        ];

        if ($signed && $time_diff > 24) {
            $result = $reward->update($data); // 更新签到时间
        } else {
            $result = $reward->store($data); // 首次签到，保存用户数据
        }

        if ($result) {
            return json('签到成功！', 'success'); // 签到成功，返回成功信息
        } else {
            return json('签到失败'); // 签到失败，返回错误信息
        }
    }

    private static function signed()
    {
        return model('reward')->checkIfSigned(session('user_id'));
    }

    private static function timeDiff()
    {
        return model('reward')->timeDiff(session('user_id'));
    }
}